package live.ifox.stage;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;

public class PositionActivity extends BaseRestActivity {
    ListView listView;
    EditText in_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position);
        actionBar.setDisplayHomeAsUpEnabled(false);

        entry = Entry.Position;
        baseUrl = Url.Position;
        in_search = findViewById(R.id.in_search);
        listView = findViewById(R.id.listView);

        in_search.setOnEditorActionListener(
                //当actionId == XX_GO 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                (v, actionId, event) -> {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                            (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode())) {
                        String kw = in_search.getText().toString();
                        if (!kw.isEmpty())
                            httpGet(baseUrl + "search/" + kw);
                    }
                    return false;   //true，保留软键盘; false，隐藏软键盘
                }
        );
    }

    public void processReply(JSONObject rootObject) {
        JSONArray array = AdapterHelper.verifyObject(rootObject, entry);
        if (array.isEmpty()) {
            listView.setAdapter(null);
            return;
        }

        List<String> items = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            String item = object.getString("topic") + "  " +
                    object.getString("label") + "  " +
                    object.getString("detail") + "  " +
                    object.getString("addition");
            if (!item.isEmpty())
                items.add(item);
        }

        ArrayAdapter<String> adapter = AdapterHelper.getArrayAdapter(this, items);
        listView.setAdapter(adapter);
    }
}
